<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          v-if="permission.active_add"
          @click.stop="handleSave"
          >新 增</el-button
        >
        <!-- <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permission.pos_staff_delete"
          @click="handleDelete"
          >删 除
        </el-button> -->
      </template>
      <template slot-scope="{ row }" slot="aisleCode">
        <span>{{ row.aisleCode }}</span>
      </template>
      <template slot-scope="{ row }" slot="agentAisleCode">
        <span>{{ row.agentAisleCode }}</span>
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <el-button
          icon="el-icon-view"
          size="small"
          type="text"
          @click.stop="handleView(row, index)"
          >查 看</el-button
        >
        <el-button
          type="text"
          icon="el-icon-edit"
          size="small"
          @click="handleEdit(row, index)"
          >编 辑</el-button
        >
      </template>
      <!-- <template slot="menuRight">
        <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="permission.pos_staff_import"
          @click="handleImport"
          >导入
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permission.pos_staff_export"
          @click="handleExport"
          >导出
        </el-button>
      </template> -->
      <!-- <template slot-scope="{ row }" slot="isOn">
        <el-switch
          :active-value="1"
          :inactive-value="0"
          v-model="row.isOn"
          @change="handleSwitch(row)"
        >
        </el-switch>
      </template> -->
    </avue-crud>
    <el-dialog
      class="avue-dialog"
      :title="dialogText + '活动'"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <unite-form
        :inputForm="activitydepositForm"
        :method="dialogType"
        ref="toActivitydepositForm"
      />
      <span slot="footer" class="dialog-footer" v-if="dialogType != 'view'">
        <el-button size="small" @click="handleSubmit" v-preventClick
          >提交</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  bankPage
} from "@/api/rb-oem/uniteOrder/unite_order";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import uniteForm from "./form/uniteForm";

export default {
  components: {
    uniteForm
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        // height: "auto",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn:false,
        selection: true,
        searchMenuSpan: 6,
        columnBtn: false,
        labelWidth:120,
        searchWidth:120,
        searchLabelWidth: 120,
        column: [
          {
            label: "主键",
            prop: "id",
            type: "input",
            sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            overHidden: true,
          },
          {
            label: "活动编号",
            prop: "activeCode",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "活动名称",
            prop: "activeName",
            search: true,
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "通道简称",
            prop: "aisleKind",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=aisle_kind",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            showColumn: false,
            search: true,
            display: false,
          },
          {
            label: "通道编号",
            searchLabel: "通道名称",
            prop: "aisleCode",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=aisle_code",
            cascader: ['bankCode'],
            props: {
              label: "dictValue",
              value: "dictKey",
              desc: "dictKey",
            },
            dataType: "string",
            showColumn: false,
            overHidden: true,
            search: true,
            display: false,
            hide: false,
            change: (item) => {
              if (item.value) {
                this.getBankPage(item.value)
              }
            },
            rules: [
              { required: true, message: '请选择通道名称', trigger: 'blur' }
            ]
          },
          {
            label: "通道名称",
            prop: "aisleName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "通道商编号",
            searchLabel: "通道商名称",
            prop: "agentAisleCode",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=agent_aisle_code",
            props: {
              label: "dictValue",
              value: "dictKey",
              desc: "dictKey",
            },
            dataType: "string",
            showColumn: false,
            overHidden: true,
            search: true,
            display: false,
            hide: false
          },
          {
            label: "通道商名称",
            prop: "agentAisleName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "银行名称",
            searchLabel: "银行名称",
            prop: "bankCode",
            type: "select",
            dicData: [],
            props: {
              label: "bankName",
              value: "bankCode",
            },
            remote: true,
            filterable: true,
            overHidden: true,
            dataType: "string",
            dicFormatter:(data)=>{
              return data.data.records
            },
            search: true,
            hide: true,
            rules: [
              { required: true, message: '请选择银行名称', trigger: 'blur' }
            ]
          },
          {
            label: "银行名称",
            prop: "bankName",
            slot: true,
            display: false,
            overHidden: true,
          },
          // {
          //   label: "活动开始日期",
          //   prop: "beginTime",
          //   type: "input",
          //   display: false,
          //   overHidden: true,
          // },
          // {
          //   label: "活动截止日期",
          //   prop: "endTime",
          //   type: "input",
          //   display: false,
          //   overHidden: true,
          // },
          // {
          //   label: "创建日期",
          //   prop: "createTime",
          //   type: "input",
          //   display: false,
          //   overHidden: true,
          // }
        ],
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-oem/oem/active/active/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
      dialogVisible: false,
      dialogType: "", //打开类型 add/edit
      dialogText: "",
      activitydepositForm: {
        activeCode: "",
        aisleKind: "",
        bankCode: "",
        activeName: "",
        aisleCode: "",
        isEnable: 1,
        subList: [
            {
                regionList: [],
                subBankName: '',
                subBankCode: '',
                activityId: '',
                subsidy: '',
                restitutionType: '',
                isEnable: '',
                $cellEdit: true
            }
        ],
        beginDate: "",
        endDate: "",
        content: "",
        timeDate: [],
      },
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.pos_staff_add, false),
        viewBtn: this.vaildData(this.permission.pos_staff_view, false),
        delBtn: this.vaildData(this.permission.pos_staff_delete, false),
        editBtn: this.vaildData(this.permission.pos_staff_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  created() {
  },
  methods: {
    handleSubmit() {
        this.$refs["toActivitydepositForm"].$refs["inputForm"].validate((valid) => {
          if (valid) {
            let regionLength = this.activitydepositForm.subList.every((val) => val.regionList.length > 0)
            if (regionLength) {
              add(this.activitydepositForm).then(
                (res) => {
                  this.dialogVisible = false;
                  this.searchReset();
                  if (res.data.code == "200") {
                    this.$message({
                      type: "success",
                      message: "操作成功!",
                    });
                  } else {
                    this.$message({
                      type: "error",
                      message: res.data.message,
                    });
                  }
                },
                (error) => {
                  window.console.log(error);
                }
              );
            } else {
              this.$message({
                type: "warning",
                message: '请配置范围后再提交',
              });
            }
          } else {
            return false;
          }
        });
    },
    /**
     * @func 新增
     * @desc 点击新增初始化显示基本信息
     * */
    handleSave() {
      this.dialogVisible = true;
      this.dialogType = "add";
      this.dialogText = "新增";
      this.activitydepositForm = {
        activeCode: "",
        aisleKind: "",
        bankCode: "",
        activeName: "",
        aisleCode: "",
        isEnable: 1,
        subList: [
            {
                regionList: [],
                subBankName: '',
                subBankCode: '',
                activityId: '',
                subsidy: '',
                restitutionType: '',
                isEnable: '',
                $cellEdit: true
            }
        ],
      }
    },
    /**
     * @func 编辑
     * @desc 点击编辑回显基本信息
     * @param {Object} row - 表格绑定的信息
     * */
    handleEdit(row) {
      this.dialogVisible = true;
      this.dialogType = "edit";
      this.dialogText = "编辑";
      getDetail({ activeCode: row.activeCode }).then((res) => {
        const data = res.data.data;
        this.$nextTick(() => {
          this.activitydepositForm = data;
        });
      });
    },
    handleView(row) {
      this.dialogVisible = true;
      this.dialogType = "view";
      this.dialogText = "查看";
      getDetail({ activeCode: row.activeCode }).then((res) => {
        const data = res.data.data;
        // this.activitydepositForm = data;
        // if (data.beginDate && data.endDate) {
        //     this.$set(data, 'timeDate', [data.beginDate, data.endDate])
        // }
        this.$nextTick(() => {
          this.activitydepositForm = data;
        });
      });
    },
     getBankPage(aisleCode){
      bankPage('-1', '-1',{aisleCode}).then( res => {
        const column = this.findObject(this.option.column, "bankCode");
        column.dicData = res.data.data.records;
      })
    },
    /**
     * @func 关闭弹窗
     * @desc 点击关闭的回调
     * @param {Function} done - 完成的回调
     * */
     handleClose(done) {
      this.$refs["toActivitydepositForm"].logoFileList = []
      this.activitydepositForm.productList = []
      this.$refs["toActivitydepositForm"].$refs["inputForm"].resetFields();
      this.onLoad(this.page, this.query);
      done();
    },
    rowSave(row, done, loading) {
      // row.isOn="1";
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.activeCode).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      let exQuery = ``;
      exQuery += `&activeCode=${this.search.activeCode}`;
      exQuery += `&activeName=${this.search.activeName}`;
      exQuery += `&beginTime=${this.search.beginTime}`;
      exQuery += `&endTime=${this.search.endTime}`;
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.open(
          `/api/rb-oem/oem/active/active/export?${
            this.website.tokenHeader
          }=${getToken()}` + exQuery
        );
      });
    },
    handleTemplate() {
      window.open(
        `/api/rb-oem/oem/active/active/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>

<style>
</style>
